<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { reqHasTrademarkAPI, reqAddorUpdataTrademarkAPI, reqDeleteTrademarkAPI } from '@/apis/product/trademark/index';
import type { HasTrademarkResponseData, Records, Trademark } from '@/apis/product/trademark/type';
import { ElMessage } from 'element-plus';
import type { UploadProps } from 'element-plus'
//当前页码
const pageNo = ref<number>(1);
//页码发生改变
const changePageNo = async () => {
    await getTrademarkList();
}
//当下拉菜单发生变化
const changePageSizes = () => {
    pageNo.value = 1;
    getTrademarkList();
}
//每一页显示数量
const limit = ref<number>(3);
// trademark列表数据
const trademarkList = ref<Records>([]);
//获取对话框表单实例
const formRef = ref();
//存储已有品牌数据数量
const total = ref<number>(0);
//发送请求获取trademark列表数据
const getTrademarkList = async () => {
    const result: HasTrademarkResponseData = await reqHasTrademarkAPI(pageNo.value, limit.value);
    if (result.code === 200) {
        trademarkList.value = result.data.records;
        total.value = result.data.total;
    }
};
onMounted(() => {
    getTrademarkList();
});
//控制对话框的显示与隐藏
const dialogFormVisible = ref<boolean>(false);
//定义一个收集添加的品牌数据
const trademarkParams = ref<Trademark>({
    tmName: '',
    logoUrl: ''
});
//点击页面添加品牌按钮
const addTrademark = () => {
    dialogFormVisible.value = true;
    trademarkParams.value.id = 0
    trademarkParams.value.tmName = ''
    trademarkParams.value.logoUrl = ''
    // 清空效验结果
    formRef.value?.clearValidate(['tmName', 'logoUrl'])
}
//点击页面编辑品牌按钮
const updateTrademark = (row: Trademark) => {
    // row 为当前点击的trademark数据
    dialogFormVisible.value = true;
    trademarkParams.value.id = row.id
    trademarkParams.value.tmName = row.tmName
    trademarkParams.value.logoUrl = row.logoUrl
    // 清空效验结果
    formRef.value?.clearValidate(['tmName', 'logoUrl'])
}
//点击页面删除品牌按钮
const deleteTrademark = async (id: number) => {
    const result = await reqDeleteTrademarkAPI(id)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        //再次发请求获取已有品牌数据
        await getTrademarkList()
    } else {
        ElMessage.error('删除失败')
    }
}
//点击对话框确定按钮
const addNewTrademark = async () => {
    //点击确定按钮的时候验证表单
    await formRef.value.validate()

    const result = await reqAddorUpdataTrademarkAPI(trademarkParams.value)
    if (result.code === 200) {
        dialogFormVisible.value = false;
        ElMessage.success(trademarkParams.value.id ? '修改成功' : '添加成功')
        //再次发请求获取已有品牌数据
        await getTrademarkList()
        trademarkParams.value.tmName = ''
        trademarkParams.value.logoUrl = ''
    } else {
        ElMessage.error(trademarkParams.value.id ? '修改失败' : '添加失败')
        dialogFormVisible.value = false;
    }

}
//点击对话框取消按钮
const cancelAdd = () => {
    trademarkParams.value.tmName = ''
    trademarkParams.value.logoUrl = ''
    dialogFormVisible.value = false;
}
//图片自定义规则
const validatatorlogoUrl = (rule: any, value: string, callback: any) => {
    if (value) {
        callback()
    } else {
        callback(new Error('请上传图片'))
    }
}
//对话框表单校验
const rules = {
    tmName: [
        { required: true, message: '请输入品牌名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    logoUrl: [
        { required: true, validatator: validatatorlogoUrl }
    ]
}
//上传图片成功之前的钩子函数，上传之前可以约束类型
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/gif') {
        ElMessage.error('上传图片类型错误')
        return false
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('图片不能超过4MB!')
        return false
    }
    return true
}
//上传成功之后的回调函数
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    trademarkParams.value.logoUrl = response.data;
    // 上传成功之后，清除对应的图片效验结果
    formRef.value.clearValidate('logoUrl')
}
</script>
<template>
    <el-card>
        <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌 </el-button>
        <!-- 表格 -->
        <el-table class="box-table" border :data="trademarkList">
            <!-- 索引列 -->
            <el-table-column label="序号" width="80" align="center" type="index"> </el-table-column>
            <!-- 名称列 -->
            <el-table-column label="品牌名称" align="left" prop="tmName"></el-table-column>
            <!-- logo列 -->
            <el-table-column label="品牌logo" align="left">
                <template #="{ row }">
                    <img :src="row.logoUrl" alt="图片" style="width:100px;height:100px;"></img>
                </template>
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="品牌操作" align="center">
                <template #="{ row }">
                    <el-button type="primary" size="small" icon="Edit" @click="updateTrademark(row)">编辑</el-button>
                    <el-popconfirm title="此操作将永久删除该文件, 是否继续?" width="250px" icon="Delete"
                        @confirm="deleteTrademark(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination @current-change="changePageNo" @size-change="changePageSizes" :pager-count="9"
            v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 10]" background
            layout="prev, pager, next, jumper, ->,sizes, total" :total="total">
        </el-pagination>
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog class="dialog-form" v-model="dialogFormVisible" :title="trademarkParams.id ? '修改品牌' : '添加品牌'">
        <el-form class="dialog-el-form" :model="trademarkParams" :rules="rules" ref="formRef">
            <el-form-item label="品牌名称" prop="tmName">
                <el-input placeholder="请输入品牌名称" v-model="trademarkParams.tmName"></el-input>
            </el-form-item>
            <el-form-item label="品牌logo" prop="logoUrl">
                <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelAdd">取 消</el-button>
                <el-button type="primary" @click="addNewTrademark">确 定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<style scoped lang="scss">
.box-table {
    margin: 10px 0
}

.dialog-form {
    width: 50%;

    .dialog-el-form {
        width: 50%;
    }

}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>